package com.hsd.netty.server.handler;

import com.hsd.netty.server.common.NettyMessage;
import com.hsd.netty.server.dispatcher.NettyHandlerDispatcher;
import com.hsd.netty.server.model.RequestObject;
import com.hsd.netty.server.model.ResultObject;
import com.hsd.netty.server.strategy.RequestMessageHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author s.he
 * on 2020/6/1
 */
@ChannelHandler.Sharable
@Service
public class RemoteServerHandler extends ChannelInboundHandlerAdapter  {
    private static final Logger logger = LoggerFactory.getLogger(RemoteServerHandler.class);

    @Autowired
    private RequestMessageHandler handler;

    public RemoteServerHandler() {
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("【开始第一层业务处理】");
        NettyMessage nettyMessage = (NettyMessage)msg;
        NettyMessage result = handler.handler(ctx, nettyMessage);
        ctx.writeAndFlush(result);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.channel().close();
    }
}
